import _ from "lodash";
import { to } from '@jzl/utils';
import {api, sapi} from "@jzl/api";
import { useDataThemeChange } from '@jzl/comps';
import { useCommonStore } from '@jzl/stores';

const { VITE_PUBLIC_PATH } = import.meta.env;

let config = {};
const setConfig = (cfg) => {
  config = Object.assign(config, cfg);
};

const getConfig = (key) => {
  if (typeof key === "string") {
    const arr = key.split(".");
    if (arr && arr.length) {
      let data = config;
      arr.forEach(v => {
        if (data && typeof data[v] !== "undefined") {
          data = data[v];
        } else {
          data = null;
        }
      });
      return data;
    }
  }
  return config;
};

/** 获取项目动态全局配置 */
export const initPlatformConfig = async (app) => {
  app.config.globalProperties.$config = getConfig();

  // TODO 临时处理，待完善
  let [ err, origConfig ] = await to(sapi.project.getProjectThemeConfig());
  /*let [ err, ret ] = await to(axios({
    method: "get",
    url: `${ VITE_PUBLIC_PATH }/platform-config.json`
  }));*/

  if(err) return;

  const { initSystemThemeConfig } = useDataThemeChange();
  let config = initSystemThemeConfig(origConfig);
  /*let config = {};

  for(let key in origConfig) {
    let value = origConfig[key];

    if(_.hasIn(value, 'attr_value')) {
      config[ key ] = value.attr_value;
    } else {
      config[ key ] = value;
    }
  }

  const store = useCommonStore();
  store.setLayout({
    layout: config.layout,
    layoutWeb: config.layoutWeb,
    layoutH5: config.layoutH5,
    theme: config.theme,
    // darkMode: false,
    // sidebarStatus: true,
    // epThemeColor: "#409EFF",
    themeColor: config.theme, // "light",
    overallStyle: config.overallStyle
  });
  store.setConfigure({
    hideTabs: config.tabStyle === 'none',
    showModel: config.tabStyle !== 'none' ? config.tabStyle : 'chrome',
    showLogo: config.showLogo == 1,
    showLogoText: config.showLogoText == 1,
  });*/

  let $config = app.config.globalProperties.$config;
  // 自动注入系统配置
  if (app && $config && typeof config === "object") {
    $config = Object.assign($config, config);
    app.config.globalProperties.$config = $config;
    // 设置全局配置
    setConfig($config);
  }
  return $config;
};

export { getConfig, setConfig };

export default initPlatformConfig;
